Dart Map operator []=
Syntax & Examples
Syntax of Map.operator []=
The syntax of Map.operator []= operator is:
operator []=(K key, V value) → voidThis operator []= operator of Map associates the key with the given value.
Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
key | required | the key to associate with the value |
value | required | the value to be associated with the key |
✐ Examples
1 Update ages in a map
In this example,
- We create a map
agescontaining names and ages. - We use the operator
[]=to associate the key 'Charlie' with the value 35 in theagesmap. - We print the updated
agesmap to standard output.
Dart Program
void main() {
Map<String, int> ages = {'Alice': 30, 'Bob': 25};
ages['Charlie'] = 35;
print('Updated ages: $ages');
}Output
Updated ages: {Alice: 30, Bob: 25, Charlie: 35}2 Update names in a map
In this example,
- We create a map
namescontaining integers and corresponding names. - We use the operator
[]=to associate the key 3 with the value 'Charlie' in thenamesmap. - We print the updated
namesmap to standard output.
Dart Program
void main() {
Map<int, String> names = {1: 'Alice', 2: 'Bob'};
names[3] = 'Charlie';
print('Updated names: $names');
}Output
Updated names: {1: Alice, 2: Bob, 3: Charlie}3 Update prices in a map
In this example,
- We create a map
pricescontaining item names and prices. - We use the operator
[]=to associate the key 'Cherry' with the value 3.0 in thepricesmap. - We print the updated
pricesmap to standard output.
Dart Program
void main() {
Map<String, double> prices = {'Apple': 2.5, 'Banana': 1.75};
prices['Cherry'] = 3.0;
print('Updated prices: $prices');
}Output
Updated prices: {Apple: 2.5, Banana: 1.75, Cherry: 3.0}Summary
In this Dart tutorial, we learned about operator []= operator of Map: the syntax and few working examples with output and detailed explanation for each example.